package com.zzyl.nursing.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
public class WechatServiceImpl implements WechatService {


    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    @Value("${wechat.AppID}")
    private String appId;
    @Value("${wechat.AppSecret}")
    private String appSecret;
    @Override
    public String getOpenId(String code) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid",appId);
        paramMap.put("secret",appSecret);
        paramMap.put("js_code",code);
        String s = HttpUtil.get(REQUEST_URL, paramMap);
        if(ObjectUtil.isNotEmpty(JSONUtil.parseObj(s).getInt("errcode"))){
            throw new BaseException( JSONUtil.parseObj(s).getStr("errmsg"));
        }
        return JSONUtil.parseObj(s).getStr("openid");
    }

    @Override
    public String getPhoneNumber(String detail_code) {
        String token = getToken();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code",detail_code);

        String jsonStr = JSONUtil.toJsonStr(paramMap);
        String result = HttpUtil.post(PHONE_REQUEST_URL + token, jsonStr);
        JSONObject j = JSONUtil.parseObj(result);
        if(j.getInt("errcode")!=0){
            throw new BaseException(j.getStr("errmsg"));
        }
        return j.getJSONObject("phone_info").getStr("phoneNumber");
    }

    private String getToken() {
        Map<String, Object> param = new HashMap<>();
        param.put("appid",appId);
        param.put("secret",appSecret);
        String s = HttpUtil.get(TOKEN_URL,param);
        if(ObjectUtil.isNotEmpty(JSONUtil.parseObj(s).getInt("errcode"))){
            throw new BaseException( JSONUtil.parseObj(s).getStr("errmsg"));
        }
        String accessToken = JSONUtil.parseObj(s).getStr("access_token");
        return accessToken;

    }
}
